import pygame,sys,os,argparse,lrc
from eyed3 import mp3
from tkinter import *
from PIL import Image,ImageTk,ImageFont
#main
os.system("cls")
os.system("mode con cols=15 lines=6")
print("主窗口")
#读入文件路径
parserz = argparse.ArgumentParser(description='music player')
parserz.add_argument("url")
args=parserz.parse_args()
try:
    link=args.url
except:
    sys.exit(0)
#函数
pauses=False
def mp3_bit(mp3Path):
        mp3Info = mp3.Mp3AudioFile(mp3Path)
        # print(mp3Info.info.bit_rate[1])
        return (mp3Info.info.bit_rate[1],mp3Info.info.time_secs)
def maths(strs):
    i=strs.split(":")
    i1=int(i[0])
    i=i[1].split(".")
    i2=int(i[0])
    i3=int(i[1])
    return i3+i2*1000+i1*60000
def pause():
    global pauses
    if not pauses:
        pygame.mixer.music.pause()
        pauseb.config(text='继续')
        pauses=True
    else:
        pygame.mixer.music.unpause()
        pauseb.config(text='暂停')
        pauses=False
def replay():
    pygame.mixer.music.load(link)
    pygame.mixer.music.play()
def updates():
    root.after(50,updates)
    pos=pygame.mixer.music.get_pos()
    if pos==-1:
        return
    sec=(pos//1000)%60
    ssec=pos%1000
    min=pos//60000
    for i,j in reversed(lrc_file.items()):
        tmp=maths(i)
        if tmp<pos:
            shi.set(str(min)+":"+str(sec)+"."+str(ssec)+"/"+str(int(long//60))+":"+str(int(long%60))+".000")
            ci.set(j)
            break
#初始化
pygame.init()
pygame.mixer.init()
#加载歌词文件
lrc_file=lrc.readLRC(link+".lrc")
title=lrc_file.pop("title","None")
people=lrc_file.pop("name","None")
#加载窗口
root=Tk()
root.title("音乐播放器")
root.geometry("450x150")
root.resizable(width=False,height=False)
#加载音乐封面
img = ImageTk.PhotoImage(Image.open(link+".jpg").resize((150,150)))
#添加窗口组件
Label(root,image=img).place(x=0,y=0)
Label(root,text=title,font=('黑体',16)).place(x=153,y=0)
Label(root,text=people,font=('等线',11)).place(x=450,y=25,anchor='ne')
ci=StringVar()
Entry(root,text=ci,state='readonly',width=41,justify='center').place(x=155,y=55)
shi=StringVar()
Entry(root,text=shi,state='readonly',width=41,justify='center').place(x=155,y=78)
pauseb=Button(root,text='暂停',font=('等线',11,'bold'),command=pause,width=15,height=2)
pauseb.place(x=155,y=105)
pauser=Button(root,text='从头开始',font=('等线',11,'bold'),command=replay,width=15,height=2)
pauser.place(x=301,y=105)
#主循环
try:
    long=mp3_bit(link)[1]
except:
    root.destroy()
    os.system("mode con cols=30 lines=10")
    print("出错啦!\nErrorCode: 1\n音乐无法播放")
    os.system('pause')
    sys.exit()
pygame.mixer.music.set_volume(0.7)
pygame.mixer.music.load(link)
pygame.mixer.music.play()
root.after(50,updates)
root.mainloop()